/*
 * Copyright (C) 2012 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.demo.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.common.network.ApiResponse;
import com.mol.market.common.network.MarketAPI;
import com.mol.market.common.util.ScreenRules;
import com.mol.market.common.util.ScreenRules.Rules;
import com.mol.market.ui.core.GridAdapter;
import com.mol.market.ui.core.GridAdapter.OnItemClickListener;
import com.mol.market.ui.core.LazyLoadAdapter;
import com.mol.market.ui_v4.ProductDetailActivity;
import com.mol.market.ui_v4.SimpleLazyLoadFragmentLoader;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * @author Chaos	
 * @Description TODO
 * @date 2013-1-11 
 */
public class RankFragment extends SimpleLazyLoadFragmentLoader
                implements android.widget.CompoundButton.OnCheckedChangeListener{
    
    protected int mCheckId = 0;
    
    private static final String KEY_CHECK_ID = "key.id.check";
    
    @Override
    protected void initAbsListView(AbsListView absListView) {
        super.initAbsListView(absListView);
        
//         View root = getAncestor().findViewById(R.id.ll_headerview_rank);
//         RadioButton rb1 = (RadioButton) root.findViewById(R.id.rb_game);
//         RadioButton rb2 = (RadioButton) root.findViewById(R.id.rb_app);
//         RadioButton rb3 = (RadioButton) root.findViewById(R.id.rb_ebook);
//         rb1.setOnCheckedChangeListener(this);
//         rb2.setOnCheckedChangeListener(this);
//         rb3.setOnCheckedChangeListener(this);
        
//        if (mCheckId != 0) {
//            ((RadioButton) root.findViewById(mCheckId)).setChecked(true);
//        }else{
//            //如果没有选中，则默认选中第一个
//            //如果不进行默认选中，则当第一个未刷出数据时，切换其它，还会发生数据
//            //混乱的Bug,原因是destroyLoader的时候id不正确
//            mCheckId = R.id.rb_game;
//        }
//        
//        handleRadionButton(rb1, rb2, rb3);
    }
    
    protected void handleRadionButton(RadioButton rb1, RadioButton rb2, RadioButton rb3) {
        //donothing
    }
    
    @Override
    protected ArrayList<HashMap<String, Object>> getDataFromResult(int method, Object obj) {
        ArrayList<HashMap<String, Object>> data = (ArrayList<HashMap<String, Object>>) ((HashMap<String, Object>) obj)
                .get(Constants.KEY_PRODUCT_LIST);
        return data;
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        if(savedInstanceState != null){
            mCheckId = savedInstanceState.getInt(KEY_CHECK_ID, 0);
        }
    }

    @Override
    protected void load() {
        getLoaderManager().restartLoader(mCheckId, null, this);
    }

    @Override
    protected LazyLoadAdapter initLazyLoadAdapter() {
        
        GridAdapter adapter = new GridAdapter(
                this, 
                null, 
                ScreenRules.getLayout(getWidthMatching(), Rules.Download),
                new String[] { 
                        Constants.KEY_PRODUCT_ICON_URL,
                        Constants.KEY_PRODUCT_NAME,
                        Constants.KEY_PRODUCT_AUTHOR,
                        Constants.KEY_PRODUCT_IS_STAR,
                        Constants.KEY_PRODUCT_DOWNLOAD,
                        Constants.KEY_PRODUCT_SIZE,
                        Constants.KEY_PRODUCT_DOWNLOAD_COUNT,
                        "flag"
                        }, 
                new int[] {
                        R.id.iv_logo,
                        R.id.tv_name,
                        R.id.tv_description,
                        R.id.iv_star,
                        R.id.tv_download,
                        R.id.tv_size,
                        R.id.tv_downloading,
                        R.id.flag
                        });
      
        adapter.setNumColumns(ScreenRules.getNumColumns(getWidthMatching(), Rules.Download));
        
        adapter.setProductList();
        
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int pos, int realPos, HashMap<String, Object> item) {
                String pid = (String) item.get(Constants.KEY_PRODUCT_ID);
                String name = (String) item.get(Constants.KEY_PRODUCT_NAME);
                Intent detailIntent = new Intent(getActivity(), ProductDetailActivity.class);
                detailIntent.putExtra(Constants.EXTRA_PRODUCT_ID, pid);
                detailIntent.putExtra(Constants.EXTRA_PRODUCT_NAME, name);
                detailIntent.putExtra(Constants.EXTRA_SOURCE_TYPE, Constants.SOURCE_TYPE_GFAN);
                getActivity().startActivity(detailIntent);
            }
        });
        
        return adapter;
    }
    
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(KEY_CHECK_ID, mCheckId);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if(isChecked){
            mCheckId = buttonView.getId();
            reset();
        }else{
            getLoaderManager().destroyLoader(buttonView.getId());
        }
    }
    
    @Override
    protected void reset() {
        super.reset();
        if(getAdapter() != null){
            getAdapter().clearData();
        }
        doLazyLoad();
    }
    
    @Override
    protected ViewGroup getCommonList(LayoutInflater inflater) {
        return (ViewGroup) inflater.inflate(R.layout.fragment_tab_rank, null);
    }
    
    @Override
    public Loader<ApiResponse> onCreateLoader(int arg0, Bundle args) {
        switch (arg0) {
        case R.id.rb_game:
            return MarketAPI.initRankByCategoryLoader(getSherlockActivity(), getStart(), getSize(),
                    Constants.CATEGORY_GAME, false);
        case R.id.rb_app:
            return MarketAPI.initRankByCategoryLoader(getSherlockActivity(), getStart(), getSize(),
                    Constants.CATEGORY_APP, false);
        case R.id.rb_ebook:
            return MarketAPI.initRankByCategoryLoader(getSherlockActivity(), getStart(), getSize(),
                    Constants.CATEGORY_EBOOK, false);
        default:
            return MarketAPI.initRankByCategoryLoader(getSherlockActivity(), getStart(), getSize(),
                    Constants.CATEGORY_GAME, false);
        }

    }

}
